package com.ouroboroswiki.core.content.velocity;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import com.ouroboroswiki.core.AbstractContent;
import com.ouroboroswiki.core.Content;
import com.ouroboroswiki.core.ContentException;

public class VelocityTemplatingContent extends AbstractContent {
	
	private Content source;
	private Map<String, Object> properties;
	private VelocityEngine engine;
	
	public VelocityTemplatingContent( VelocityEngine engine, Content source, Map<String, Object> properties ) {
		this.engine = engine;
		this.source = source;
		this.properties = properties;
	}

	@Override
	public Map<String, Content> getChildContent() {
		HashMap<String, Content> children = new HashMap<String, Content>(1);
		children.put( Content.CHILD_CONTENT_MAIN, this.source );
		return children;
	}

	@Override
	public void write(OutputStream outs) throws IOException, ContentException {
		// transform using velocity
		VelocityContext context = new VelocityContext(properties);
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		source.write(bos);
		String template = new String( bos.toByteArray() );
		OutputStreamWriter writer = new OutputStreamWriter( outs );
		engine.evaluate(context, writer, this.getUniqueName()+"."+this.getRepositoryName(), template);
		writer.flush();
	}

}
